package org.example;

import org.example.model.*;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) throws ParseException {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistCustomer(emf);
    }
    private static void persistPerson(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Person p1 = new Person("Lindsey Craft",Arrays.asList("111-111-111","222-222-222"));
        Person p2 = new Person("Morgan Philips",Arrays.asList("333-333-333"));
        em.getTransaction().begin();
        em.persist(p1);
        em.persist(p2);
        em.getTransaction().commit();
        em.close();
    }
    private static void persistCustomer(EntityManagerFactory emf) throws ParseException {
        System.err.println("-- Persisting entities --");
        EntityManager em = emf.createEntityManager();
        Customer c1 = new Customer();
        c1.setName("Lindsey");
        c1.setPhoneNumbers(Arrays.asList(
                new PhoneNumber("111-111-111", PhoneType.Cell),
                new PhoneNumber("222-222-222",PhoneType.House)
        ));

        Map<String,Integer> itemPurchased = new HashMap<>();
        itemPurchased.put("XYZ Blender",1);
        itemPurchased.put("ZZZ Beer Glass",2);
        c1.setItemQtyMap(itemPurchased);
        c1.addOrder("online","XYZ Blender",2);
        c1.addOrder("store","ZZZ Beer Glass",4);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Task task1 = new Task();
        task1.setName("test 1");
        task1.setDescription("task 1 desc");
        Task task2 = new Task();
        task2.setName("test 2");
        task2.setDescription("test 2 desc");
        c1.addTask(format.parse("2017-01-15"),task1);
        c1.addTask(format.parse("2017-01-20"),task2);

        Customer c2 = new Customer();
        c2.setName("Morgan Philips");
        c2.setPhoneNumbers(Arrays.asList(
                new PhoneNumber("333-333-333",PhoneType.Work)
        ));

        Map<String,Integer> orderMap = new HashMap<>();
        orderMap.put("AA Glass Cleaner",3);
        c2.setItemQtyMap(orderMap);
        c2.addOrder("online","AA Glass Cleaner",3);

        Task task3 = new Task();
        task3.setName("task 3");
        task3.setDescription("task 3 desc");
        c2.addTask(format.parse("2017-02-15"),task3);

        em.getTransaction().begin();
        em.persist(task1);
        em.persist(task2);
        em.persist(task3);
        em.persist(c1);
        em.persist(c2);
        em.getTransaction().commit();
        em.close();
    }
}
